package com.darcytech.debezium.core.pool;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;

public class ConnectionWrap {

    private final Connection connection;

    private Boolean healthy;

    private LocalDateTime errorTime;


    public Connection getConnection() {
        return connection;
    }

    public Boolean getHealthy() {
        return healthy;
    }

    public LocalDateTime getErrorTime() {
        return errorTime;
    }

    public void setHealthy(Boolean healthy) {
        this.healthy = healthy;
    }

    public void setErrorTime(LocalDateTime errorTime) {
        this.errorTime = errorTime;
    }

    public ConnectionWrap(Connection connection, Boolean healthy, LocalDateTime errorTime) {
        this.connection = connection;
        this.healthy = healthy;
        this.errorTime = errorTime;
    }

    public String genServerId() {
        Statement stmt = null;
        ResultSet rs = null;

        try {
            if (!getHealthy()) {
                return null;
            }
            stmt = connection.createStatement();
            rs = stmt.executeQuery("SELECT @@server_id as SERVER_ID;");
            if (rs.next()) {
                return rs.getString("SERVER_ID");
            } else {
                return null;
            }
        } catch (SQLException e) {
            return null;
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }

            } catch (SQLException closeException) {
            }
        }
    }
}
